<template>
  <div v-if=" !isForgot " class="layout" id="layout-body">
    <div class="left">
      <h3>Welcome !</h3>

      <div class="group-2">
        <p>Sign in to</p>
        <p>Lorem Ipsum is simply</p>
      </div>

      <div class="group-3">
        <div class="input-group">
          <el-form
            class="demo-ruleForm"
            ref="iptRef"
            :model="user"
            :rules="rules"
            status-icon
            hide-required-asterisk
            @keyup.enter="handleLogin( iptRef )"
          >
            <el-form-item label="User name" prop="username" label-position="top">
              <input v-model="user.username" type="text" placeholder="Enter your user name" />
            </el-form-item>
            <el-form-item label="Password" prop="password" label-position="top">
              <input
                v-model="user.password"
                type="password"
                placeholder="Enter your Password"
                show-password
              />
            </el-form-item>
            <el-form-item label="Verification Code" prop="code" label-position="top">
              <el-row>
                <el-col :span="18">
                  <input v-model="user.code" type="text" placeholder="Enter Verification Code" />
                </el-col>
                <el-col :span="6">
                  <div class="vcode" @click="changeVcode">
                    <text>{{ codeNum }}</text>
                    <el-image class="el-image" fit="cover" :src="codeImg" />
                  </div>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
        </div>
        <div class="check-group">
          <el-checkbox v-model="isChecked" label="Rememebr me" />
          <p @click="isForgot = true">Forgot Password ?</p>
        </div>
        <button class="btn-group" @click="handleLogin( iptRef )">Login</button>
      </div>

      <div class="group-4">
        Don’y have an Account ？
        <router-link to="/register">Register</router-link>
      </div>
    </div>
    <div class="right">
      <img src="../../assets/images/login/login-right.png" alt="" />
    </div>
  </div>

  <template v-else>
    <Forgot @close="isForgot = false" />
  </template>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getUserLoginApi } from '@/apis/index'
import { useUserStore } from '@/stores/user.js'
import { useRouter } from 'vue-router'
import Forgot from './components/forgot.vue'

const router = useRouter()
const userStore = useUserStore()
const isForgot = ref(false)
const isChecked = ref(false)
const iptRef = ref()
const codeNum = ref(0)
const codeImg = ref('https://web-tilas4854.oss-cn-beijing.aliyuncs.com/ranking/8.png')

const user = reactive({
  username: '',
  password: '',
  code: ''
})

const vcodeImgList = [
  'https://web-tilas4854.oss-cn-beijing.aliyuncs.com/ranking/8.png',
  'https://web-tilas4854.oss-cn-beijing.aliyuncs.com/ranking/9.png',
  'https://web-tilas4854.oss-cn-beijing.aliyuncs.com/ranking/10.png',
  'https://web-tilas4854.oss-cn-beijing.aliyuncs.com/ranking/11.png',
  'https://web-tilas4854.oss-cn-beijing.aliyuncs.com/ranking/12.png'
]

const codeNumList = [
  'A',
  'B',
  'C',
  'D',
  'E',
  'F',
  'G',
  'H',
  'I',
  'J',
  'K',
  'L',
  'M',
  'N',
  'O',
  'P',
  'Q',
  'R',
  'S',
  'T',
  'U',
  'V',
  'W',
  'X',
  'Y',
  'Z',
  '0',
  '1',
  '2',
  '3',
  '4',
  '5',
  '6',
  '7',
  '8',
  '9'
]

const checkCode = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('Please Enter Verification Code'))
  } else if (value.toUpperCase() !== codeNum.value) {
    callback(new Error('The code is incorrect'))
  } else {
    callback()
  }
}

const rules = reactive({
  username: [
    { min: 3, message: 'Min Length should be 3', trigger: 'blur' },
    { required: true, message: 'Please input your username', trigger: 'change' }
  ],
  password: [
    { required: true, message: 'Please input your password', trigger: 'change' },
    { min: 6, message: 'Min Length should be 6 ', trigger: 'blur' }
  ],
  code: [
    { validator: checkCode, trigger: 'blur' },
    { required: true, message: 'Please input your Verification Code', trigger: 'change' },
    { min: 4, message: 'Min Length should be 4 ', trigger: 'blur' }
  ]
})

const getCodeNum = () => {
  // 随机四位字符 -> 验证码
  let val = ''
  for (let i = 0; i < 4; i++) {
    val += codeNumList[Math.floor(Math.random() * codeNumList.length)]
  }
  codeNum.value = val
}

// 修改验证码背景图
const changeVcode = () => {
  const index = Math.floor(Math.random() * vcodeImgList.length)
  codeImg.value = vcodeImgList[index]
  getCodeNum()
}

// 提交表单
const handleLogin = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (
      valid &&
      user.username.trim().length &&
      user.password.trim().length &&
      user.code.toUpperCase() === codeNum.value
    ) {
      console.log('提交成功', user)
      const { code, message, data } = await getUserLoginApi({
        username: user.username,
        password: user.password
      })
      if (code === 200) {
        ElNotification({
          title: '查询成功',
          message: message,
          type: 'success'
        })
        userStore.setUser(user.username, user.password, data)
        router.push('/findmusic/recommend')
      } else {
        ElNotification({
          title: '查询失败',
          message: message,
          type: 'warning'
        })
        user.username = ''
        user.password = ''
        user.code = ''
      }
    } else {
      if (fields.code) {
        user.username = ''
        user.password = ''
        user.code = ''
      } else {
        user.username = ''
        user.password = ''
      }
      changeVcode()
      console.log('error submit!', fields)
    }
  })
}

// // 重置表单
// const resetForm = () => {
//   loginFormRef.value.resetFields()
// }

onMounted(() => {
  const DEFAULT_SCREEN = {
    width: 1920,
    height: 1580
  }
  // 只考虑长>宽的情形
  const setDOMStyle = () => {
    const dom = document.getElementById('layout-body')

    const height = (DEFAULT_SCREEN.height * window.innerHeight) / DEFAULT_SCREEN.width

    // const width = (DEFAULT_SCREEN.width * window.innerWidth) / DEFAULT_SCREEN.height
    dom.style.height = height + 'px'
    // dom.style.width = width + 'px'
  }
  window.onresize = setDOMStyle
  getCodeNum()
  setDOMStyle()
})
</script>

<style lang="scss" scoped>
.layout {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #dedede;

  .left {
    padding: 36px 35px;
    margin-left: 111px;
    width: 505px;
    min-height: 701px;
    border: 0.5px solid #878787;
    box-shadow: 0px 4px 64px 0px rgba(0, 0, 0, 0.05);

    h3 {
      font-size: 25px;
      font-weight: 300;
      line-height: 35px;
      color: #000000;
    }

    .group-2 {
      font-size: 31px;
      font-weight: 500;
      line-height: 43px;
      color: #000000;
    }

    .group-3 {
      margin-top: 50px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
      width: 423px;
      height: 415px;

      .input-group {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: space-between;
        width: 100%;

        .el-form {
          width: 100%;
          height: 100%;

          .el-form-item {
            input {
              padding-left: 17px;
              width: 100%;
              height: 59px;
            }

            input::-webkit-input-placeholder {
              font-size: 18px;
              font-weight: 300;
              line-height: 20px;
              color: #ababab;
            }

            input:focus {
              outline: none;
            }
          }
        }
      }

      .check-group {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;

        p {
          cursor: pointer;
          font-size: 14px;
          font-weight: 300;
          line-height: 17px;
          color: #000000;
        }
      }

      .btn-group {
        width: 100%;
        height: 57px;
        color: #fff;
        background-color: #000000;
      }
    }

    .group-4 {
      margin-top: 56px;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      font-weight: 300;
      font-size: 16px;
      color: #7d7d7d;

      a {
        font-weight: 600;
        font-size: 16px;
        color: #000000;
        text-decoration: none;
      }
    }
  }

  .right {
    width: 827px;
    height: 650px;

    img {
      width: 100%;
      height: 100%;
    }
  }
}

.vcode {
  position: relative;
  margin-left: auto;
  width: 90%;
  height: 60px;
  border-radius: 15px;
  overflow: hidden;

  text {
    z-index: 999;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 24px;
    font-weight: 300;
    line-height: 20px;
    background: linear-gradient(to right, #ec008c, #fc6767);
    -webkit-background-clip: text;
    /*将设置的背景颜色限制在文字中*/
    -webkit-text-fill-color: transparent;
    /*给文字设置成透明*/
  }

  input {
    width: 100%;
    height: 100%;
    border: none;
    padding-left: 17px;
    opacity: 0.5;
  }

  .el-image {
    width: 100%;
    height: 100%;
  }

  &::before {
    content: '';
    z-index: 999;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 60px;
    opacity: 1;
    border-radius: 5px;
    background: rgba(0, 0, 0, 0.01);
    backdrop-filter: blur(18px);
  }
}

.el-row {
  width: 100%;
}

:deep(.el-checkbox__input .is-checked .is-focus) {
  color: #ababab;
}
</style>
